<!--
 * @file 列表轮播组件
 * @author its-wild(https://gitee.com/its-wild)
 * @date 2022/11/06
-->
<template>
  <div
    ref="swipeListCtn"
    class="swipe-list"
    :style="{
      margin: `${px2rem(option.top) || 0} ${px2rem(option.bottom) || 0}`,
      paddingLeft:spacing,
      paddingRight:spacing
    }"
  >
    <cell-title
      :title="option.title"
      :hide-desc="option.isMore === '2'"
      :next-url="moreLink"
      :style="{
        'background-color': option.backgroundColor,
        'border-radius':
          px2rem(option.radiusSize) + ' ' + px2rem(option.radiusSize) + ' 0 0'
      }"
    />
    <van-swipe
      :id="'courseSwiperIndex' + key"
      ref="swiper"
      :duration="1000"
      touchable
      :indicator-color="mainColor"
      :stop-propagation="false"
      :loop="false"
      :style="{
        'background-color': option.backgroundColor,
        'border-radius':
          '0 0 ' + px2rem(option.radiusSize) + ' ' + px2rem(option.radiusSize)
      }"
      @change="handleChange"
    >
      <van-swipe-item
        v-for="(item, i) in list"
        :key="i"
        :style="{ width: px2rem(swiperItemWidth) }"
      >
        <section
          v-for="(ite, j) in item"
          :key="i + '-' + j"
          class="course-swiper-item"
          :class="[Object.keys(ite).length === 0 && 'last']"
          @click="toDetail(ite)"
        >
          <div
            class="item-img"
            :style="{
              height: px2rem(option.itemHeight),
              'border-radius': px2rem(option.imgRadiusSize)
            }"
          >
            <van-image :src="ite.courseImgUrl">
              <template v-slot:loading>
                <van-loading type="spinner" size="20" />
              </template>
              <template v-slot:error>
                <img
                  src="../../images/base/error-icon.png"
                  alt
                >
              </template>
            </van-image>
          </div>
          <div class="item-info">
            <div class="item-title etc">
              <span>{{ ite.courseName }}</span>
            </div>
            <div v-if="Object.keys(ite).length > 0" class="item-number">
              <!-- <span>浏览人次：{{ ite.pageview || 0 }}</span> -->
            </div>
          </div>
        </section>
      </van-swipe-item>
    </van-swipe>
  </div>
</template>

<script>
import qs from 'qs'
import { v4 as uuidv4 } from 'uuid'
import mixins, { getVar } from './../mixins'
import CellTitle from './cellTitle.vue'

const defImg = ''
export default {
  name: 'SwipeList',
  components: {
    CellTitle
  },
  mixins: [mixins],
  props: {
    option: {
      type: Object,
      default() {
        return {}
      }
    },
    isInitData: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      defImg,
      mainColor: '#fff',
      currentIndex: '',
      key: uuidv4(),
      defaultList: [
        {
          id: 'Z1488017664152432641',
          courseName: '列表标题',
          pageview: 3047,
          courseImgUrl: defImg
        },
        {
          id: 'Z1488017664152432641',
          courseName: '列表标题',
          pageview: 3047,
          courseImgUrl: defImg
        },
        {
          id: 'Z1488017664152432641',
          courseName: '列表标题',
          pageview: 3047,
          courseImgUrl: defImg
        },
        {
          id: 'Z1488017664152432641',
          courseName: '列表标题',
          pageview: 3047,
          courseImgUrl: defImg
        },
        {
          id: 'Z1488017664152432641',
          courseName: '列表标题',
          pageview: 3047,
          courseImgUrl: defImg
        },
        {
          id: 'Z1488017664152432641',
          courseName: '列表标题',
          pageview: 3047,
          courseImgUrl: defImg
        },
        {
          id: 'Z1488017664152432641',
          courseName: '列表标题',
          pageview: 3047,
          courseImgUrl: defImg
        },
        {
          id: 'Z1488017664152432641',
          courseName: '列表标题',
          pageview: 3047,
          courseImgUrl: defImg
        },
        {
          id: 'Z1488017664152432641',
          courseName: '列表标题',
          pageview: 3047,
          courseImgUrl: defImg
        }
      ],
      list: [],
      pageSize: '',
      courseClassify: '',
      courseLabel: '',
      courseBelong: '',
      moreLink: ''
    }
  },
  computed: {
    swiperItemWidth() {
      return Math.floor((750 - this.option.spacing * 2) * 0.76)
      // return this.px2rem(Math.floor((750 - this.option.spacing * 2) * 0.76))
    }
  },
  watch: {
    'option.pageSize': {
      handler(v) {
        if (!this.isInitData && this.defaultList && this.defaultList.length) {
          this.list = this.arrTrans(v, this.defaultList)
        }
      },
      immediate: true
    }
  },
  async created() {
    if (this.isInitData) {
      this.courseClassify = this.option.origin === 1 ? this.option.classify4company.split('/').reverse()[0] : this.option.classify4platform.split('/').reverse()[0]
      this.courseLabel = this.option.origin === 1 ? this.option.label4company : this.option.label4platform
      this.courseBelong = this.option.origin === 1 || this.option.origin === 2 ? 1 : 2
      this.pageSize = this.option.pageSize * this.option.column
      await this.initData()
      this.moreLink = this.getMoreDetail('moreLink')
    } else {
      this.list = this.arrTrans(3, this.defaultList)
    }
  },
  methods: {
    /**
     * 用于initData方法调用完设置数据
     */
    setData(result) {
      const { rows } = result.dataList?.data
      this.list = this.arrTrans(this.option.pageSize, rows)
    },
    // 去详情
    toDetail(item) {
      let detailsLink = this.option.detailsLink
      if (detailsLink) {
        const queryStr = detailsLink.split('?')[1]
        const query = qs.parse(queryStr)
        Object.entries(query).forEach((x) => {
          const val = x[1]
          if (val.startsWith('${') && val.endsWith('}')) {
            const field = val.slice(2, val.length - 1)
            detailsLink = detailsLink.replace('${' + field + '}', item[field])
          }
        })
        window.location.href = detailsLink
      }
    },
    handleChange(index) {
      if (index === this.list.length - 1) {
        setTimeout(() => {
          document.querySelector(
            `#courseSwiperIndex${this.key} .van-swipe__track`
          ).style.transform = `translateX(${
            this.swiperItemWidth * index * -1
          }px)`
        }, 10)
      }
    },
    /**
     * 数组分页
     */
    arrTrans(num, arr) {
      const array = []
      arr.forEach((item, index) => {
        const page = Math.floor(index / num)
        if (!array[page]) {
          array[page] = []
        }
        array[page].push(item)
      })
      return array
    },
    /**
     * 跳转页面
     */
    goPage(item) {
      if (item.link) {
        window.location.href = item.link
      }
    },
    getVar(varStr = '', index = 1) {
      if (varStr) {
        const reg = /\$\{(.+?)\}/
        return varStr.match(reg)[1].split('|')[index]
      } else {
        return ''
      }
    },
    getMoreDetail(field = 'link') {
      const linkData = this.option && this.option[field]
      if (linkData) {
        // 跳转内部链接 或自定义页面
        if (linkData.type === 'inside' || linkData.type === 'other') {
          // 判断跳转链接是否有参数，如果有参数，需要把参数获取回来，并且设置对应字段
          // 参数数组
          const paramsList = linkData.params
            ? JSON.parse(linkData.params)
            : []
          const queryObj = {}
          paramsList.forEach((x) => {
            const { keyCode, keyValue } = x
            const keyType = this.getVar(keyValue, 0)
            const key = this.getVar(keyValue)
            if (keyType === 'route') {
              queryObj[keyCode] = this.$route.query[key]
            } else if (keyType === 'self') {
              queryObj[keyCode] = this[key]
            } else {
              // 当前组件上的某个变量上的值
              queryObj[keyCode] = this[keyType][key]
            }
          })
          let param = ''
          for (const key in queryObj) {
            param += key + '=' + (queryObj[key] || '') + '&'
          }
          param = param.substring(0, param.length - 1)
          return linkData.link + '?' + param
        } else if (linkData.type === 'outside') {
          return linkData.link
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
@import '@/styles/utility/rem.scss';
.swipe-list {
  width: rem(750);
  overflow: hidden;
}

.van-swipe {
  width: 100%;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;
  border-radius: 0 0 rem(16) rem(16);
  background-color: #fff;

  .van-swipe-item {
    background: none;
    padding: 0 rem(20) rem(30);

    .course-swiper-item {
      padding: rem(20) 0;
      position: relative;
      display: flex;
      &:first-child {
        padding-top: 0;
      }
      &:last-child:after {
        display: none;
      }
      &.last:after {
        display: none;
      }
      &:after {
        left: 0;
        right: 0;
        width: auto;
        height: 1px;
        position: absolute;
        z-index: 0;
        bottom: 0;
        content: '';
        background-image: -webkit-linear-gradient(
          bottom,
          #ececec 50%,
          transparent 0
        );
        background-image: linear-gradient(0deg, #ececec 50%, transparent 0);
      }

      .item-img {
        flex: 0 0 auto;
        width: rem(186);
        height: 100%;
        margin-right: rem(20);
        overflow: hidden;

        .van-image {
          width: 100%;
          height: 100%;
        }
        img {
          position: relative;
          height: 100%;
          width: 100%;
          border-radius: rem(8);
        }
      }
      .item-info {
        height: rem(114);
        flex: auto;
        overflow: hidden;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        padding: rem(8) 0;
        .item-title {
          width: 100%;
          font-size: rem(28);
          font-family: PingFang SC Medium, PingFang SC Medium-Medium;
          font-weight: bold;
          text-align: left;
          color: #333333;
        }
        .item-number {
          font-size: rem(24);
          font-family: PingFang SC Regular, PingFang SC Regular-Regular;
          font-weight: 400;
          text-align: left;
          color: #999999;
          span:first-child {
            margin-right: rem(20);
          }
        }
      }
    }
  }
}
</style>
